import { useState, useEffect, useCallback } from 'react'
import { useHistory, useLocation, useRouteMatch } from 'react-router-dom'

function useSelected () {
  let [selected, setSelected] = useState('cookbook')
  let { pathname } = useLocation()
  let history = useHistory()
  let match = useRouteMatch()

  useEffect(
    () => {
      let regExp = new RegExp('\\/home\\/(\\w+)', 'gi')
      regExp.exec(pathname)
      setSelected(RegExp.$1)
    }, 
    [pathname]
  )

  const handlePress = useCallback(
    (key) => {
      const prevKey = selected
      return () => {
        setSelected(key)
        if (prevKey === key) return
        history.push(`${match.url}/${key}`)
      }
    },
    [selected, history, match]
  )

  return {
    selected,
    handlePress
  }
}

export default useSelected